<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 250px;
            height: 150px;
            background-color: #ccc;
            margin: 0 auto;
            padding: 30px 10px;
        }

        .box div {
            margin: 20px 0;
        }

        .box input {
            border: 0;
            outline: none;
        }

        .box button {
            width: 100%;
            display: inline-block;
            background-color: rgb(248, 28, 28);
            color: white;
            border: 0;
            height: 30px;
            cursor: pointer;

        }
    </style>
</head>

<body>
    <h1>登录</h1>
    <div class="box">
        <form action="" method="post">
            <div>
                用户名：<input type="text" name="userName" id="" autocomplete="off">
            </div>
            <div>
                密 码: &nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="userPwd" id="" autocomplete="off">
            </div>

            <button type="submit">登录</button>
        </form>
    </div>
    <script>
        const form = document.forms[0];

        form.onsubmit = function (e) {
            e.preventDefault();

            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        if (xhr.response.flag) {
                            alert(xhr.response.msg)
                            localStorage.setItem('token', xhr.response.token);//将数据库中的taken储存到本地
                            location.replace('index.html')
                        } else {
                            alert(xhr.response.msg)
                        }
                        console.log(xhr.response);
                    } else {
                        alert('出错了123')
                    }
                }
            }

            xhr.open('post', '/admin/login', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.responseType = 'json';
            xhr.send(JSON.stringify({
                userName: form.userName.value,
                userPwd: form.userPwd.value,
            }))
        }
    </script>
</body>

</html>